package com.toycloud.config.controller;

import cn.dev33.satoken.sso.SaSsoProcessor;
import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.toycloud.business.dto.results.UserParam;
import com.toycloud.common.sso.api.RemoteSsoService;
import com.toycloud.common.sso.enums.DeviceType;
import com.toycloud.system.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.toycloud.interceptor.HeaderInterceptor.APPID;

/**
 * @author hlchan
 * @version 1.0
 * @date 2024/9/18 17:41
 */
@RestController
@Slf4j
@RequestMapping("/sso")
public class SsoClientController {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RemoteSsoService remoteSsoService;

    /**
     * 当前是否登录
     */
    @RequestMapping("/isLogin")
    public Object isLogin() {
        return SaResult.data(StpUtil.isLogin());
    }

    /**
     * 返回SSO认证中心登录地址
     */
    @RequestMapping("/getSsoAuthUrl")
    public SaResult getSsoAuthUrl(String clientLoginUrl) {
        String serverAuthUrl = SaSsoUtil.buildServerAuthUrl(clientLoginUrl, "");
        return SaResult.data(serverAuthUrl);
    }

    /**
     * 根据ticket进行登录
     */
    @RequestMapping("/ssoLoginByTicket")
    public SaResult doLoginByTicket(String ticket) {
        Object loginId = SaSsoProcessor.instance.checkTicket(ticket, "/sso/ssoLoginByTicket");
        if(loginId != null) {
            StpUtil.login(loginId, DeviceType.PC.getDevice());

            UserParam userParam = new UserParam();
            String token = jwtUtil.generateToken(loginId.toString());
            userParam.setToken(token);

            try {
                //获取用户信息
                Object o = remoteSsoService.getUserInfo(APPID, loginId);
                if (o instanceof Map) {
                    Map<String, Object> resultMap = (Map<String, Object>) o;
                    if((int)resultMap.get("code")==200){
                        Map<String, Object> userInfoMap = (Map<String, Object>)resultMap.get("data") ;
                        userParam.setUserid( (String) userInfoMap.get("userid"));
                        userParam.setUsername((String) userInfoMap.get("username"));
                    }
                }
            } catch (Exception e){
                log.error(e.getMessage());
                return SaResult.error("登录错误，获取用户信息失败，请联系管理员！");
            }
            return SaResult.data(userParam);
        }
        return SaResult.error("无效ticket：" + ticket);
    }

    /**
     * 单点注销
     */
    @RequestMapping("/logout")
    public Object ssoRequest() {
        return SaSsoProcessor.instance.ssoLogout();
    }

    /**
     * 单点注销回调接口
     */
    @RequestMapping("/logoutCall")
    public Object logoutCall() {
        return SaSsoProcessor.instance.ssoLogoutCall();
    }

}